//
//  MainNavigationController.swift
//  MoodDiary
//
//  Created by MoodDiary on 2020/11/24.
//

import UIKit

class MainNavigationController: UINavigationController {
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }

    var popDelegate: UINavigationControllerDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white

        navigationBar.barStyle = .black
        navigationBar.barTintColor = .white
        navigationBar.tintColor = .black
        navigationBar.shadowImage = UIImage()
        navigationBar.setBackgroundImage(UIImage(), for: .default)
        
        
        navigationBar.titleTextAttributes = [.font: UIFont.systemFont(ofSize: 18.5, weight: .medium), .foregroundColor: UIColor.black]
        
        popDelegate = interactivePopGestureRecognizer?.delegate as? UINavigationControllerDelegate
        delegate = self
    }
    
    @objc func backAction() {
        popViewController(animated: true)
    }
    
    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        
        if viewControllers.count >= 1 {
            viewController.hidesBottomBarWhenPushed = true
        }
        
        super.pushViewController(viewController, animated: true)
        
        guard viewController != viewControllers.first else { return }
        
        viewController.navigationItem.leftBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "返回"), style: .plain, target: self, action: #selector(backAction))
        
        if viewController is DiaryEditViewController {
            navigationBar.titleTextAttributes = [.font: UIFont.systemFont(ofSize: 18.5, weight: .medium), .foregroundColor: UIColor.hexColor(hex: "#808080")]
        } else {
            navigationBar.titleTextAttributes = [.font: UIFont.systemFont(ofSize: 18.5, weight: .medium), .foregroundColor: UIColor.black]
        }
        
    }
    
}

extension MainNavigationController: UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        guard viewController == viewControllers.first else {
            interactivePopGestureRecognizer?.delegate = nil
            return
        }
        interactivePopGestureRecognizer?.delegate = popDelegate as? UIGestureRecognizerDelegate
        
    }
}
